package com.ruoyi.system.netty;

import cn.hutool.core.lang.Console;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

@ChannelHandler.Sharable
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    static final EventExecutorGroup group = new DefaultEventExecutorGroup(30);
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //IdleStateHandler心跳机制,如果超时触发Handle中userEventTrigger()方法
        pipeline.addLast(new IdleStateHandler(50,0,0, TimeUnit.SECONDS));
        pipeline.addLast(new ChannelDuplexHandler(){
            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                IdleStateEvent event=(IdleStateEvent)evt;
                if(event.state()== IdleState.READER_IDLE){
                    InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
                    String clientIp = ipSocket.getAddress().getHostAddress();
                    System.out.println(clientIp+"：已经有50s没有读到数据了");
                    //关闭设备连接...
                    ctx.channel().close();
                }
            }
        });
//        //自定义编解码器
//        pipeline.addLast(
//                new MessagePacketDecoder(),
//                new MessagePacketEncoder()
//        );
        //pipeline.addLast(new ByteArrayEncoder());
        //自定义StringDecoder，其余的都是用的netty提供的
        pipeline.addLast(new MyStringDecoder());
        //自定义Hadler
        pipeline.addLast(group,"handler",new TCPServerHandler());
    }
}
